import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Select, InputNumber, Upload, Image } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { ProductApi, Spu, ProductCategoryVO, ProductBrandVO } from '../../../api/mall/product';

const { Option } = Select;
const { TextArea } = Input;

const MallProduct: React.FC = () => {
  const [products, setProducts] = useState<Spu[]>([]);
  const [categories, setCategories] = useState<ProductCategoryVO[]>([]);
  const [brands, setBrands] = useState<ProductBrandVO[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Spu | null>(null);
  const [form] = Form.useForm();

  // 获取商品列表
  const fetchProducts = async () => {
    setLoading(true);
    try {
      const response = await ProductApi.getSpuPage({});
      setProducts(response.data?.list || []);
    } catch (error) {
      message.error('获取商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await ProductApi.getCategoryList();
      setCategories(response.data || []);
    } catch (error) {
      message.error('获取分类列表失败');
    }
  };

  // 获取品牌列表
  const fetchBrands = async () => {
    try {
      const response = await ProductApi.getBrandPage({});
      setBrands(response.data?.list || []);
    } catch (error) {
      message.error('获取品牌列表失败');
    }
  };

  useEffect(() => {
    fetchProducts();
    fetchCategories();
    fetchBrands();
  }, []);

  // 新增/编辑商品
  const handleSave = async (values: any) => {
    try {
      const productData = {
        ...values,
        sliderPicUrls: values.sliderPicUrls?.map((file: any) => file.url || file.response?.url).filter(Boolean) || [],
      };

      if (editingProduct) {
        await ProductApi.updateSpu({ ...editingProduct, ...productData });
        message.success('更新商品成功');
      } else {
        await ProductApi.createSpu(productData);
        message.success('创建商品成功');
      }
      setModalVisible(false);
      setEditingProduct(null);
      form.resetFields();
      fetchProducts();
    } catch (error) {
      message.error(editingProduct ? '更新商品失败' : '创建商品失败');
    }
  };

  // 删除商品
  const handleDelete = async (id: number) => {
    try {
      await ProductApi.deleteSpu(id);
      message.success('删除商品成功');
      fetchProducts();
    } catch (error) {
      message.error('删除商品失败');
    }
  };

  // 打开编辑模态框
  const openEditModal = (product: Spu) => {
    setEditingProduct(product);
    form.setFieldsValue({
      ...product,
      sliderPicUrls: product.sliderPicUrls?.map((url, index) => ({
        uid: index.toString(),
        name: `image-${index}`,
        status: 'done',
        url,
      })) || [],
    });
    setModalVisible(true);
  };

  // 打开新增模态框
  const openAddModal = () => {
    setEditingProduct(null);
    form.resetFields();
    setModalVisible(true);
  };

  const columns = [
    {
      title: '商品图片',
      dataIndex: 'picUrl',
      key: 'picUrl',
      render: (picUrl: string) => (
        <Image
          width={60}
          height={60}
          src={picUrl}
          fallback=""
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      key: 'categoryId',
      render: (categoryId: number) => {
        const category = categories.find(c => c.id === categoryId);
        return category?.name || '-';
      },
    },
    {
      title: '品牌',
      dataIndex: 'brandId',
      key: 'brandId',
      render: (brandId: number) => {
        const brand = brands.find(b => b.id === brandId);
        return brand?.name || '-';
      },
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '虚拟销量',
      dataIndex: 'virtualSalesCount',
      key: 'virtualSalesCount',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Spu) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px' }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={openAddModal}
        >
          新增商品
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={products}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      <Modal
        title={editingProduct ? '编辑商品' : '新增商品'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingProduct(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnClose
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Form.Item
            name="name"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>
          
          <Form.Item
            name="categoryId"
            label="商品分类"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select placeholder="请选择商品分类">
              {categories.map(category => (
                <Option key={category.id} value={category.id}>
                  {category.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="brandId"
            label="商品品牌"
          >
            <Select placeholder="请选择商品品牌" allowClear>
              {brands.map(brand => (
                <Option key={brand.id} value={brand.id}>
                  {brand.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="keyword"
            label="关键字"
          >
            <Input placeholder="请输入关键字" />
          </Form.Item>

          <Form.Item
            name="unit"
            label="单位"
          >
            <InputNumber placeholder="请输入单位" style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="picUrl"
            label="商品主图"
          >
            <Input placeholder="请输入商品主图URL" />
          </Form.Item>

          <Form.Item
            name="sliderPicUrls"
            label="商品轮播图"
          >
            <Upload
              listType="picture-card"
              multiple
              beforeUpload={() => false}
            >
              <div>
                <UploadOutlined />
                <div style={{ marginTop: 8 }}>上传</div>
              </div>
            </Upload>
          </Form.Item>

          <Form.Item
            name="introduction"
            label="商品简介"
          >
            <TextArea placeholder="请输入商品简介" rows={3} />
          </Form.Item>

          <Form.Item
            name="description"
            label="商品详情"
          >
            <TextArea placeholder="请输入商品详情" rows={4} />
          </Form.Item>

          <Form.Item
            name="sort"
            label="排序"
          >
            <InputNumber placeholder="请输入排序" style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="virtualSalesCount"
            label="虚拟销量"
          >
            <InputNumber placeholder="请输入虚拟销量" style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MallProduct;